<template>
  <div class="app-container">
    <div class="collect-ota">
      <h2>升级包名称:{{detailInfo.name}}<span> 版本号:{{detailInfo.ver}}</span></h2>
      <el-form v-column="4" :model="dataFilter" ref="formRef">

        <el-form-item label="" prop="type">
          <el-radio-group v-model="type" @change="onTab">
            <el-radio-button label="批次管理" value="1" />
            <el-radio-button label="设备列表" value="2" />
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select 
              v-if="type === '1'"
              v-model="dataFilter.status" 
              clearable 
              placeholder="请选择"
            >
              <el-option label="待开始" :value="0" />
              <el-option label="进行中" :value="1" />
              <el-option label="已完成" :value="2" />
              <el-option label="未完成" :value="3" />
            </el-select>
            <el-select 
              v-else-if="type === '2'"
              v-model="dataFilter.status" 
              clearable 
              placeholder="请选择"
            >
              <el-option label="待推送" :value="0" />
              <el-option label="已推送" :value="1" />
              <el-option label="升级中" :value="2" />
              <el-option label="升级成功" :value="3" />
              <el-option label="升级失败" :value="4" />
            </el-select>
          </el-form-item>

        <el-form-item label="升级批次ID" prop="batchIdStr">
          <el-input v-model="dataFilter.batchIdStr" placeholder="请输入"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>

      <div v-if="type === '1'">
        <el-table
          :data="sourceData.list"
          highlight-current-row
          stripe
        >
          <el-table-column label="升级批次ID" prop="id" />
          <el-table-column label="批次类型" prop="batchType">
            <template #default="{ row }">
              <span>{{ row.batchType === 1 ? '全部' : '定向' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备数量" prop="equipNum" />
          <el-table-column label="状态" prop="status">
            <!-- 四种状态 -->
            <template #default="{ row }">
              <span v-if="row.status === 0">待开始</span>
              <span v-else-if="row.status === 1">进行中</span>
              <span v-else-if="row.status === 2">已完成</span>
              <span v-else="row.status === 3">未完成</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime" />
          <el-table-column label="操作" align="center" width="220">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleView(row)">
                详情
              </el-button>
              <el-button
                v-if="row.status === 3"
                type="primary" 
                link 
                @click="handleRetry(row)"
              >
                重试
              </el-button>
              <el-button
                v-if="row.status === 0"
                type="primary" 
                link 
                @click="handleUpdate(row)"
              >
                立即升级
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination :pageProps="pageProps" layout="prev, pager, next" @current-change="getList" />
      </div>

      <div v-else-if="type === '2'">
        <el-table
          :data="sourceData2.list"
          highlight-current-row
          stripe
        >
          <el-table-column label="设备名称" prop="equipName" />
          <el-table-column label="设备MAC" prop="macCode" />
          <el-table-column label="升级批次ID" prop="batchId" />
          <el-table-column label="当前版本号" prop="pkgVersion" />
          <el-table-column label="升级状态" prop="status">
            <!-- 四种状态 -->
            <template #default="{ row }">
              <span v-if="row.status === 0">待推送</span>
              <span v-else-if="row.status === 1">已推送</span>
              <span v-else-if="row.status === 2">升级中</span>
              <span v-else-if="row.status === 3">升级成功</span>
              <span v-else="row.status === 4">升级失败</span>
            </template>
          </el-table-column>
          <el-table-column label="状态更新时间" prop="updateTime" />
        </el-table>
        <Pagination :pageProps="pageProps2" layout="prev, pager, next" @current-change="getList2" />

      </div>
    
    </div>
  </div>

  <OtaDialog ref="dialog" @listChange="itemData" />
  <OtaMultiDialog ref="dialog2" @listChange="itemData" />
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { otaBatchList, otaRetry, otaUpgrade, otaEquipList, gatewayDetail } from '@/api/collect'
import Pagination from '@/components/Pagination/Index.vue'
import OtaDialog from './components/OtaDialog.vue'
import OtaMultiDialog from './components/OtaMultiDialog.vue'

const formRef = ref()

const dataFilter = reactive({
  id: null,
  status: null,
  batchIdStr: '',
})

const detailInfo = reactive({
  name: null,
  ver: null,
})

const route = useRoute()

detailInfo.name = route.query.name
detailInfo.ver = route.query.ver

dataFilter.id = route.query.id

const pageProps = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})

const type = ref('1')

const sourceData = reactive({
  list: [] as any,
})

const getList = () => {
  otaBatchList({
    pageNum: pageProps.value.pageNum,
    pageSize: pageProps.value.pageSize,
    ...dataFilter
  }).then((res)=>{
    console.log('res', res)
    sourceData.list = res.data.records
    // TODO use real api total res total
    pageProps.value.total = res.data.total
  })
  .catch((err) => {
    console.error('err', err)
  })
}

getList()

const pageProps2 = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})

const sourceData2 = reactive({
  list: [] as any,
})

const getList2 = () => {
  otaEquipList({
    pageNum: pageProps2.value.pageNum,
    pageSize: pageProps2.value.pageSize,
    ...dataFilter
  }).then((res)=>{
    console.log('res', res)
    sourceData2.list = res.data.records
    // TODO use real api total res total
    pageProps2.value.total = res.data.total
  })
  .catch((err) => {
    console.error('err', err)
  })
}

// getList2()

const onTab = () => {
  if (type.value === '1') {
    dataFilter.status = null,
    dataFilter.batchIdStr = ''
    getList()
  } else {
    dataFilter.status = null,
    dataFilter.batchIdStr = ''
    getList2()
  }
}

const onSearch = () => {
  if (type.value === '1') {
    getList()
  } else {
    getList2()
  }
}

const dialog: any = ref(null)

const handleView = (row: any) => {
  console.log('row', row)
  type.value = '2'
  dataFilter.batchIdStr = row.id
  getList2()
}

const dialog2: any = ref(null)

const handleRetry = (row: any) => {
  // dialog2.value.dialogVisible = true
  // dialog2.value.dialogStatus = 'edit'
  const params = {
    id: row.id
  }
  otaRetry(params)
  .then((res)=>{
    console.log('res', res)
    ElMessage.success('重试成功！')
    getList()
  })
  .catch((err)=>{
    console.error('err', err)
    ElMessage.error('重试失败！' + err.msg)
  })
}

const itemData = () => {
  getList()
}

const handleUpdate = (row: any) => {
  ElMessageBox.confirm(
    '确定要立即升级吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {  
    const params = {
      id: row.id
    }
    otaUpgrade(params)
    .then((res: any) => {
      ElMessage.success('更新成功！')
      getList()
    })
    .catch((err: any) => {
      console.error('err', err.msg)
      ElMessage.error('更新失败！' + err.msg)
    })
  })
  .catch(() => {})
}
</script>

<style scoped>
.app-container {
  flex: 1;
  .collect-ota {
    h2 {
      font-size: 16px;
      margin: 13px 0 24px;
      span {
        display: inline-block;
        padding: 0 8px;
        line-height: 20px;
        font-size: 12px;
        font-weight: 400;
        margin-left: 8px;
        color: #fff;
        background: #F7B955;
        border-radius: 2px;
      }
    }
  }
}
</style>